#!/usr/bin/python3
# -*- coding: utf-8 -*-
import base64
import hashlib
from hashlib import sha256
import hmac
from typing import Text
import binascii

from cryptography.fernet import Fernet
from pyDes import des, ECB, PAD_PKCS5


def hmac_sha256_encryption(key, data):
    """hmac sha 256算法"""
    _key = key.encode('utf8')
    _data = data.encode('utf8')
    encrypt_data = hmac.new(_key, _data, digestmod=sha256).hexdigest()
    return encrypt_data


def sha256_encryption(_str: Text):
    """ sha 256 加密"""
    str_md5 = hashlib.sha256(_str.encode('utf-8')).hexdigest()
    return str_md5


def sha1_encryption(_str: Text):
    """
    使用sha1加密算法，返回str加密后的字符串
    """
    encrypts = hashlib.sha1(_str.encode('utf-8')).hexdigest()
    return encrypts


def sha512_encryption(_str: Text):
    """ sha 512 加密"""
    str_md5 = hashlib.sha512(_str.encode('utf-8')).hexdigest()
    return str_md5


def md5_encryption(value):
    """ md5 加密"""
    str_md5 = hashlib.md5(str(value).encode(encoding='utf-8')).hexdigest()
    return str_md5


def base64_encode(data: Text):
    # Base64编码
    return base64.b64encode(data.encode())


def base64_decode(data: Text):
    # Base64解码
    return base64.b64decode(data).decode()


def des_encryption(_str):
    """
    DES 加密
    :return: 加密后字符串，16进制
    """
    # 密钥，自行修改
    _key = 'PASSWORD'
    secret_key = _key
    _iv = secret_key
    key = des(secret_key, ECB, _iv, pad=None, padmode=PAD_PKCS5)
    _encrypt = key.encrypt(_str, padmode=PAD_PKCS5)
    return binascii.b2a_hex(_encrypt)




def aes_encryption(plaintext, key):
    """
       使用AES加密算法对明文进行加密

       参数:
       key (str): 加密解密使用的密钥，必须是32个字符以内的字符串
       plaintext (str): 待加密的明文

       返回:
       str: 加密后的密文
       """
    key = key.encode()
    if len(key) > 32:
        raise ValueError("密钥长度不能超过32个字符")

    # TODO: 优先级-5 这样调用为何不成功？
    f = Fernet(key)
    ciphertext = f.encrypt(plaintext.encode())

    return ciphertext.decode()
def aes_decrypt(enc_data, key):
    """
    Decrypt AES encrypted data.

    Args:
    enc_data (str): Encrypted data to be decrypted.
    key (str): Secret key used for encryption.

    Returns:
    str: Decrypted data.
    """
    # Convert key to bytes
    key = key.encode()

    # Convert encrypted data to bytes
    enc_data_bytes = base64.b64decode(enc_data)

    # Generate Fernet cipher using the key
    #TODO: 优先级-5 这样调用为何不成功？
    cipher_suite = Fernet(key)

    # Decrypt data
    decrypted_data = cipher_suite.decrypt(enc_data_bytes)

    return decrypted_data.decode()
def encryption(ency_type):
    """
    :param ency_type: 加密类型
    :return:
    """

    def decorator(func):
        def swapper(*args, **kwargs):
            res = func(*args, **kwargs)
            _data = res['body']
            if ency_type == "md5":
                def ency_value(data):
                    if data is not None:
                        for key, value in data.items():
                            if isinstance(value, dict):
                                ency_value(data=value)
                            else:
                                data[key] = md5_encryption(value)
            else:
                raise ValueError("暂不支持该加密规则，如有需要，请联系管理员")
            ency_value(_data)
            return res

        return swapper

    return decorator
if __name__ == '__main__':
    # from cryptography.fernet import Fernet

    print(hmac_sha256_encryption('1', '2'))
    print(sha256_encryption('1'))
    print(sha512_encryption('1'))
    print(md5_encryption('1'))
    print(sha1_encryption('1'))
    print(des_encryption('1'))


    data= "Hello, World!"
    # data=data.encode()
    # encoded_data = base64.b64encode(data)
    # print(encoded_data)
    # decoded_data = base64.b64decode(encoded_data)
    # print(decoded_data)
    # # 解码
    # decoded_data_str = decoded_data.decode()
    # print(decoded_data_str)

    print(base64_encode(data))


    decrypted_data = aes_decrypt('SGVsbG8sIFdvcmxkIQ==', 'SecretKey')
    print(decrypted_data)